//提示信息对象
let msg;
//列对象
let cols;
layui.config({
    base: '../lay/dist/'
});
layui.use(['form', 'table', 'laydate', 'notice'], function () {
    var $ = layui.jquery,
        form = layui.form,
        table = layui.table,
        laydate = layui.laydate,
        notice = layui.notice;
    msg = layui.notice;
    /**
     * 表格主题渲染
     */
    table.render({
        elem: '#classRoom',
        url: 'class-room/all',
        method: 'post',
        parseData: function (res) {
            return {
                "code": res.success == true ? 0 : 1,
                "count": res.total,
                "data": res.data

            }
        },
        toolbar: '#toolbarDemo',
        defaultToolbar: ['filter', 'exports', 'print', {
            title: '提示',
            layEvent: 'LAYTABLE_TIPS',
            icon: 'layui-icon-tips'
        }],
        cols: [
            [
                {
                    field: 'xid', width: 300, title: '序号', sort: true, templet: function (d) {
                        return d.LAY_INDEX;
                    }
                },
                {field: 'id', width: 100, title: 'ID', sort: true, hide: true},

                {field: 'roomname', width: 250, title: '教室名称', edit: 'date'},

                {field: 'roomdesc', width: 250, title: '教室描述', edit: 'text'},

                {title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"}

            ]
        ],
        limits: [10, 15, 20, 25, 50, 100],
        limit: 15,
        page: true,
        skin: 'line'
    });

    /**
     * 监听搜索操作
     */
    form.on('submit(data-search-btn)', function (data) {
        var result = data.field;
        console.log(result)
        //执行搜索重载
        table.reload('classRoom', {
            url: 'class-room/likeAll',
            method: 'post'
            , where: {
                classRoomName: result.classRoom,
            }
        }, 'data');
        notice.success("搜索执行成功！");
        return false;

    });
    /**
     * 监听表格编辑
     */
    table.on('edit(currentTableFilter)', function(obj){
        var value = obj.value //得到修改后的值
            ,data = obj.data //得到所在行所有键值
            ,lal = obj.field; //得到字段
        $.post("class-room/upDate",{
            id:data.id,
            roomname: data.roomname,
            roomdesc:data.roomdesc,
        },function (result) {
            if (result.success == true) {
                notice.success("修改成功！");
            }else {
                notice.error("修改失败！");
            }
        })
    });

    /**
     * 嘿，靓仔，这是又一个按钮(添加)
     * 第一个ajxa是来判断参数是否存在，存在错误提示，不存在继续
     * 第二个ajax是用来提交操作，提交后成功，重载表格，并且清空输入框内容 #add 是form 表单的id
     * 其实还有很多骚操作，不需要写这么多请求，但是这样逻辑清晰
     */
    form.on('submit(data-add)', function (data) {
        var add = data.field;
        $.post("class-room/existClassRoom", {roomName: add.classRoom}, function (result) {
            if (result >= 1) {
                notice.error("教室已经存在！");
            }else {
                $.post("class-room/add",{
                    roomname: add.classRoom,
                    roomdesc:add.classRoomDesc,

                },function (result) {
                    if (result.success == true) {
                        table.reload('classRoom', {
                            url: 'class-room/all',
                            method: 'post'
                        }, 'data');
                        notice.success("添加成功！");
                        $("#add")[0].reset();
                    }else {
                        notice.error("添加失败！");
                    }
                })
            }
        })

    });
    /**
     * toolbar监听事件
     */
    table.on('toolbar(currentTableFilter)', function (obj) {
        if (obj.event === 'selectAll') { //
            table.reload('classRoom', {
                url: 'class-room/all',
                method: "post"
            })
            notice.success("查询成功！");
        }
    });
    /**
     * 工具行监听(删除/编辑)
     * */
    table.on('tool(currentTableFilter)', function (obj) {
        let data = obj.data;
        cols = obj;
        if (obj.event === 'edit') {
            let index = layer.open({
                title: '编辑用户',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                area: ['100%', '100%'],
                content: 'studentEdit?id=' + data.id,
            });
            $(window).on("resize", function () {
                layer.full(index);
            });
            return false;
        } else if (obj.event === 'delete') {
            layer.confirm('是否要删除此条记录？', function (index) {

                $.post("class-room/del", {id: obj.data.id}, function (result) {
                    if (result.success != true) {
                        notice.warning("删除失败！");
                    } else {
                        notice.success("删除成功！");
                        obj.del()
                    }
                })
                layer.close(index);
            }, function (index) {
                layer.close(index);
            });

        }

    });
    /**
     * 时间戳的处理
     * @param d
     * @param format
     * @returns {string}
     */
    layui.laytpl.toDateString = function (d, format) {
        var date = new Date(d || new Date())
            , ymd = [
            this.digit(date.getFullYear(), 4)
            , this.digit(date.getMonth() + 1)
            , this.digit(date.getDate())
        ]
            , hms = [
            this.digit(date.getHours())
            , this.digit(date.getMinutes())
            , this.digit(date.getSeconds())
        ];

        format = format || 'yyyy-MM-dd';

        return format.replace(/yyyy/g, ymd[0])
            .replace(/MM/g, ymd[1])
            .replace(/dd/g, ymd[2])
            .replace(/hh/g, hms[0])
            .replace(/mm/g, hms[1])
            .replace(/ss/g, hms[2]);
    };
    /**
     * 数字前置补零
     * @param num
     * @param length
     * @param end
     * @returns {*}
     */
    layui.laytpl.digit = function (num, length, end) {
        var str = '';
        num = String(num);
        length = length || 2;
        for (var i = num.length; i < length; i++) {
            str += '0';
        }
        return num < Math.pow(10, length) ? str + (num | 0) : num;
    };
    /**
     * 时间选择器自定义颜色
     */
    laydate.render({
        elem: '#begin'

        , theme: '#393D49'
    });
    laydate.render({
        elem: '#end'

        , theme: '#393D49'
    });


    /**
     * 设置提示信息属性
     * @type {{hideEasing: string, positionClass: string, hideDuration: string, debug: boolean, closeButton: boolean, extendedTimeOut: string, showEasing: string, onclick: null, showDuration: string, iconClass: string, timeOut: string}}
     */
    notice.options = {
        closeButton: true,//显示关闭按钮
        debug: false,//启用debug
        positionClass: "toast-bottom-right",//弹出的位置,
        showDuration: "300",//显示的时间
        hideDuration: "1000",//消失的时间
        timeOut: "2000",//停留的时间
        extendedTimeOut: "1000",//控制时间
        showEasing: "swing",//显示时的动画缓冲方式
        hideEasing: "linear",//消失时的动画缓冲方式
        iconClass: 'toast-info', // 自定义图标，有内置，如不需要则传空 支持layui内置图标/自定义iconfont类名
        onclick: null, // 点击关闭回调
    };

    // notice.warning("");信息状态
    // notice.info("");
    // notice.error("");
    // notice.success("");
});


function parentPage(result, childData) {
    if (result.success == true) {
        cols.update({
            className: childData.className,
            studentName: childData.studentName,
            date: childData.beginTime,
            factperson: childData.factPerson,
            remarks: childData.remarks,
            upstage: childData.upStage,
            warncount: childData.warnCount,
            work: childData.work
        })

        msg.info("修改成功");
        return;
    }
    msg.warning("修改失败")
}